package com.ruyiadmin.springboot.web_api.aspects.framework;

import cn.hutool.core.util.StrUtil;
import com.google.common.util.concurrent.RateLimiter;
import com.ruyiadmin.springboot.common_infrastructure.exceptions.TooManyRequestsException;
import com.ruyiadmin.springboot.web_api.annotations.framework.SimpleRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <p>
 * 系统限流切面定义
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-11-02
 */
@Slf4j
@Aspect
@Component
public class SimpleRateLimiterAspect {

    /**
     * 高并发单机缓存
     */
    private static final ConcurrentMap<String, RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();

    /**
     * 系统限流切面入口
     */
    @Pointcut("@annotation(com.ruyiadmin.springboot.web_api.annotations.framework.SimpleRateLimiter)")
    public void rateLimit() {

    }

    /**
     * 系统限流切面环听
     */
    @Around("rateLimit()")
    public Object pointcut(ProceedingJoinPoint point) throws Throwable {

        //获取SimpleRateLimiter注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SimpleRateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, SimpleRateLimiter.class);

        if (rateLimiter != null && rateLimiter.qps() > 0) {

            // 初始化 QPS
            double qps = rateLimiter.qps();
            String key = method.getDeclaringClass().getName() + StrUtil.DOT + method.getName();
            if (RATE_LIMITER_CACHE.get(key) == null) {
                RATE_LIMITER_CACHE.put(key, RateLimiter.create(qps));
            }

            // 尝试获取令牌
            if (RATE_LIMITER_CACHE.get(key) != null
                    && !RATE_LIMITER_CACHE.get(key).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) {
                throw new TooManyRequestsException("too many requests");
            }
        }

        return point.proceed();
    }
}
